from django.shortcuts import render
from django.views.generic import View
from django.http import HttpResponse
from .models import *
from .forms import ArticleForm

# Create your views here.


class IndexView(View):
    def get(self, request, *args, **kwargs):
        # return HttpResponse('GET request!')
        return render(request, 'index.html')

    def post1(self, request, *args, **kwargs):
        myfile = request.FILES.get('thumbnial')
        with open('somefile.txt', 'wb') as fp:
            for chunk in myfile.chunks():
                fp.write(chunk)
        return HttpResponse('POST request!')

    def post2(self, request, *args, **kwargs):
        title = request.POST.get('title')
        content = request.POST.get('content')
        thumbnial = request.FILES.get('thumbnial')
        Article(title=title, content=content, thumbnial=thumbnial).save()
        return HttpResponse('POST request!')

    def post(self, request):
        form = ArticleForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponse('POST success!')
        else:
            print(form.errors.get_json_data())
            return HttpResponse('POST error!')
